package BitCreeekClient;

import javax.net.ServerSocketFactory;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class PeerP2PServerThread implements Runnable {

    private ExecutorService workers;

    /**
     * Porta TCP su cui viene bindato il P2P server
     */
    private int port;
    private String torrentName;

    /**
     * Costruttore di TrackerTCPThread
     *
     * @param port        port
     * @param torrentName torrnent name
     */
    public PeerP2PServerThread ( int port, String torrentName ) {
        this.port = port;
        this.torrentName = torrentName;
        workers = Executors.newCachedThreadPool ();
    }

    public void run () {
        try {
            
            ServerSocketFactory serversocketfactory = ServerSocketFactory.getDefault ();
            ServerSocket serversocket = serversocketfactory.createServerSocket ( this.port );

            while ( true ) {
                Socket ss = serversocket.accept ();
                workers.execute ( new PeerP2PServerWorker ( torrentName, ss ) );
            }

        } catch ( Exception e ) {
            e.printStackTrace ();
        }

    }
}
